# Maintainer: Martell Malone <martellmalone@gmail.com>
# Maintainer: Alexey Pavlov <alexpux@gmail.com>
# Contributor: Ray Donnelly <mingw.android@gmail.com>
# Contributor: Mateusz Mikuła <mati865@gmail.com>
# Contributor: wirx6 <wirx654@gmail.com>
# Contributor: Yuui Tanabe <yuuitanabe@163.com>
# Contributor: Oscar Fuentes <ofv@wanadoo.es>
# Contributor: Adrian Pop <adrian.pop@liu.se>

if [[ $MINGW_PACKAGE_PREFIX == *-clang-* ]]; then
  _clangprefix=1
fi

_realname=llvm
pkgbase=mingw-w64-${_realname}-16
pkgname=("${MINGW_PACKAGE_PREFIX}-${_realname}-16"
         "${MINGW_PACKAGE_PREFIX}-clang-16"
         "${MINGW_PACKAGE_PREFIX}-compiler-rt-16")
_version=16.0.6
_rc=""
_tag=llvmorg-${_version}${_rc}
pkgver=${_version}${_rc/-/}
pkgrel=2
pkgdesc="C language family frontend for LLVM 16 (mingw-w64)"
arch=('any')
mingw_arch=('mingw64' 'ucrt64' 'clang64' 'clangarm64')
url="https://llvm.org/"
license=("spdx:Apache-2.0 WITH LLVM-exception")
makedepends=("${MINGW_PACKAGE_PREFIX}-cc"
             "${MINGW_PACKAGE_PREFIX}-cmake"
             "${MINGW_PACKAGE_PREFIX}-z3"
             "${MINGW_PACKAGE_PREFIX}-libffi"
             "${MINGW_PACKAGE_PREFIX}-ninja"
             "${MINGW_PACKAGE_PREFIX}-pkgconf"
             "${MINGW_PACKAGE_PREFIX}-python"
             "git")
_url=https://github.com/llvm/llvm-project/releases/download/${_tag}
source=("${_url}/llvm-${pkgver}.src.tar.xz"{,.sig}
        "${_url}/clang-${pkgver}.src.tar.xz"{,.sig}
        "${_url}/compiler-rt-${pkgver}.src.tar.xz"{,.sig}
        "${_url}/cmake-${pkgver}.src.tar.xz"{,.sig}
        "0001-Fix-GetHostTriple-for-mingw-w64-in-msys.patch"
        "0002-Revert-CMake-try-creating-symlink-first-on-windows.patch"
        "0003-add-pthread-as-system-lib-for-mingw.patch"
        "0004-enable-emutls-for-mingw.patch"
        "0005-Fix-Any-linker-error-with-multiple-compilers.patch"
        "0101-link-pthread-with-mingw.patch"
        "https://github.com/llvm/llvm-project/commit/ab8d4f5a122fde5740f8c084c8165f51a26c93c7.patch")
# Some patch notes :)
#0001-0099 -> llvm
#0101-0199 -> clang
#0201-0299 -> rt
sha256sums=('e91db44d1b3bb1c33fcea9a7d1f2423b883eaa9163d3d56ca2aa6d2f0711bc29'
            'SKIP'
            '1186b6e6eefeadd09912ed73b3729e85b59f043724bb2818a95a2ec024571840'
            'SKIP'
            '7911a2a9cca10393a17f637c01a6f5555b0a38f64ff47dc9168413a4190bc2db'
            'SKIP'
            '39d342a4161095d2f28fb1253e4585978ac50521117da666e2b1f6f28b62f514'
            'SKIP'
            'eb03df53671df6627768141b3aaa76abe176a14e5e47911c97bec544387c4aff'
            '5754c357cfc17769e80d95b673d41b1e54616e2487e037d761a1ac8bb28a2849'
            '7f0c64cd87b61e894be632f180ae5291e1aa9f1d9d382608f659067eeeda7146'
            'ef2ae12a4d6ac7a52d38bb305818b26c830ae42d14468e4b1913157d998b2137'
            '294756995c1d528f9b5d4b64559edfee151ce0a06bd863a2cafce58a82ce53fd'
            '715cb8862753854b2d9256e0b70003e2d1f57083d83eaeaf5a095fc72b8a4e26'
            '614a86cb22d3785d8099760c00f3981908c9a97b65b280e7350ee5dd1a0967bd')
validpgpkeys=('B6C8F98282B944E3B0D5C2530FC3042E345AD05D'  # Hans Wennborg, Google.
              '474E22316ABF4785A88C6E8EA2C794A986419D8A'  # Tom Stellard
              'D574BD5D1D0E98895E3BF90044F2485E45D59042') # Tobias Hieta
noextract=(clang-${pkgver}.src.tar.xz)

apply_patch_with_msg() {
  for _patch in "$@"
  do
    msg2 "Applying ${_patch}"
    patch -Nbp1 -i "${srcdir}/${_patch}"
  done
}

prepare() {
  cd "${srcdir}"
  plain "Extracting clang-${pkgver}.src.tar.xz due to symlink(s) without pre-existing target(s)"
  tar -xJf "${srcdir}"/clang-${pkgver}.src.tar.xz -C "${srcdir}" || true

  # Rename Directories
  for pkg in llvm clang compiler-rt cmake; do
    mv ${pkg}-$pkgver.src ${pkg}
  done

  # https://github.com/llvm/llvm-project/issues/63132
  apply_patch_with_msg \
    ab8d4f5a122fde5740f8c084c8165f51a26c93c7.patch

  # Patch llvm
  cd "${srcdir}/llvm"
  apply_patch_with_msg \
    "0001-Fix-GetHostTriple-for-mingw-w64-in-msys.patch" \
    "0002-Revert-CMake-try-creating-symlink-first-on-windows.patch" \
    "0005-Fix-Any-linker-error-with-multiple-compilers.patch"

  if (( ! _clangprefix )); then
    apply_patch_with_msg \
      "0003-add-pthread-as-system-lib-for-mingw.patch" \
      "0004-enable-emutls-for-mingw.patch"
  fi

  # Patch clang
  cd "${srcdir}/clang"

  if (( ! _clangprefix )); then
    apply_patch_with_msg \
      "0101-link-pthread-with-mingw.patch"
  fi
}

build() {
  cd "${srcdir}"

  local -a platform_config
  local -a common_cmake_args

  if check_option "debug" "y"; then
    common_cmake_args+=(-DCMAKE_BUILD_TYPE=Debug)
    VERBOSE="VERBOSE=1"
  else
    common_cmake_args+=(-DCMAKE_BUILD_TYPE=Release)
  fi
  common_cmake_args+=(-Wno-dev
    -DCMAKE_INSTALL_PREFIX=${MINGW_PREFIX}/opt/llvm-16
    -DDEFAULT_SYSROOT="../../.."
    -DCMAKE_SYSTEM_IGNORE_PATH=/usr/lib
    -DLLVM_HOST_TRIPLE="${CARCH}-w64-windows-gnu"
    -DPython3_EXECUTABLE=${MINGW_PREFIX}/bin/python.exe)

  # Include location of libffi headers in CPPFLAGS
  FFI_INCLUDE_DIR="$(pkg-config --cflags libffi)"
  FFI_INCLUDE_DIR=$(echo $FFI_INCLUDE_DIR | sed 's|-I||g')

  if (( _clangprefix )); then

    platform_config+=(-DCLANG_DEFAULT_RTLIB=compiler-rt
      -DCLANG_DEFAULT_UNWINDLIB=libunwind
      -DCLANG_DEFAULT_CXX_STDLIB=libc++
      -DCOMPILER_RT_USE_BUILTINS_LIBRARY=ON
      -DLLVM_ENABLE_LIBCXX=ON
      -DCLANG_DEFAULT_LINKER=lld
      -DLLVM_ENABLE_LLD=ON)
  fi

  local _projects="clang;compiler-rt"

  platform_config+=(-DLLVM_TARGETS_TO_BUILD="AArch64;ARM;RISCV;X86")

  mkdir -p build-${MSYSTEM} && cd build-${MSYSTEM}

  MSYS2_ARG_CONV_EXCL="-DCMAKE_INSTALL_PREFIX=;-DDEFAULT_SYSROOT=" \
  ${MINGW_PREFIX}/bin/cmake.exe \
    -GNinja \
    -DFFI_INCLUDE_DIR="${FFI_INCLUDE_DIR}" \
    -DLIBCLANG_BUILD_STATIC=ON \
    -DLLVM_BUILD_STATIC=ON \
    -DLLVM_ENABLE_ASSERTIONS=OFF \
    -DLLVM_ENABLE_FFI=ON \
    -DLLVM_ENABLE_PROJECTS="${_projects}" \
    -DLLVM_ENABLE_THREADS=ON \
    -DLLVM_ENABLE_RTTI=ON \
    -DLLVM_INCLUDE_EXAMPLES=OFF \
    -DLLVM_INCLUDE_BENCHMARKS=OFF \
    -DLLVM_INCLUDE_TESTS=OFF \
    -DLLVM_INCLUDE_UTILS=ON \
    "${common_cmake_args[@]}" \
    "${platform_config[@]}" \
    ../llvm

  ${MINGW_PREFIX}/bin/cmake.exe --build .
}

package_compiler-rt-16() {
  pkgdesc="Runtime libraries for Clang and LLVM 16 (mingw-w64)"
  url="https://compiler-rt.llvm.org/"
  depends=("${MINGW_PACKAGE_PREFIX}-gcc-libs")

  DESTDIR="${pkgdir}" ${MINGW_PREFIX}/bin/cmake --install "${srcdir}/build-${MSYSTEM}/projects/compiler-rt"

  mkdir -p "${pkgdir}${MINGW_PREFIX}/opt/llvm-16/bin/"
  find "${pkgdir}${MINGW_PREFIX}/opt/llvm-16/lib/clang/${_version%.[0-9].*}/lib/windows/" \
    -name '*.dll' -exec mv '{}' "${pkgdir}${MINGW_PREFIX}/opt/llvm-16/bin/" \;
  # remove bin dir we created if it is still empty
  rmdir "${pkgdir}${MINGW_PREFIX}/opt/llvm-16/bin/" 2>/dev/null || true
}

package_clang-16() {
  pkgdesc="C language family frontend for LLVM 16 (mingw-w64)"
  url="https://clang.llvm.org/"
  depends=("${MINGW_PACKAGE_PREFIX}-llvm-16"
           "${MINGW_PACKAGE_PREFIX}-compiler-rt-16" \
           $( ((_clangprefix)) && echo \
             "${MINGW_PACKAGE_PREFIX}-crt" \
             "${MINGW_PACKAGE_PREFIX}-headers" \
             "${MINGW_PACKAGE_PREFIX}-lld" \
             "${MINGW_PACKAGE_PREFIX}-winpthreads" \
             || echo "${MINGW_PACKAGE_PREFIX}-gcc"))

  DESTDIR="${pkgdir}" ${MINGW_PREFIX}/bin/cmake --install "${srcdir}/build-${MSYSTEM}/tools/clang"
}

package_llvm-16() {
  pkgdesc="Low Level Virtual Machine - 16 (mingw-w64)"
  depends=("${MINGW_PACKAGE_PREFIX}-gcc-libs")

  # Disable automatic installation of components that go into subpackages
  # -i.orig to check what has been removed in-case it starts dropping more than it should
  #
  sed -i.orig '/clang\/cmake_install.cmake/d' "${srcdir}/build-${MSYSTEM}"/tools/cmake_install.cmake
  sed -i.orig '/compiler-rt\/cmake_install.cmake/d' "${srcdir}/build-${MSYSTEM}"/projects/cmake_install.cmake

  DESTDIR="${pkgdir}" cmake --install "${srcdir}/build-${MSYSTEM}"

  install -Dm644 "${srcdir}/llvm/LICENSE.TXT" "${pkgdir}${MINGW_PREFIX}/opt/llvm-16/share/licenses/llvm/LICENSE"

  # Install CMake stuff
  install -d "${pkgdir}"${MINGW_PREFIX}/opt/llvm-16/share/llvm/cmake/{modules,platforms}
  install -Dm644 "${srcdir}"/llvm/cmake/modules/*.cmake "${pkgdir}"${MINGW_PREFIX}/opt/llvm-16/share/llvm/cmake/modules/
  install -Dm644 "${srcdir}"/llvm/cmake/platforms/*.cmake "${pkgdir}"${MINGW_PREFIX}/opt/llvm-16/share/llvm/cmake/platforms/

  # fix cmake files.
  local PREFIX_WIN=$(cygpath -wm ${MINGW_PREFIX})
  sed -e "s|${PREFIX_WIN}|${MINGW_PREFIX}|g" -i "${pkgdir}"/${MINGW_PREFIX}/opt/llvm-16/lib/cmake/llvm/LLVMExports.cmake
}

# template start; name=mingw-w64-splitpkg-wrappers; version=1.0;
# vim: set ft=bash :

# generate wrappers
for _name in "${pkgname[@]}"; do
  _short="package_${_name#${MINGW_PACKAGE_PREFIX}-}"
  _func="$(declare -f "${_short}")"
  eval "${_func/#${_short}/package_${_name}}"
done
# template end;
